/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.ibatis.extension.keygen;

import com.je.ibatis.extension.toolkit.Constants;
import com.je.ibatis.extension.toolkit.ParameterUtil;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.springframework.util.StringUtils;

import java.sql.Statement;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 元数据UUID主键策略
 * <p>
 * 插入前使用UUID生成主键,加入parameter的Map中
 *
 * @author wangmm@ketr.com.cn
 * @date 2019/11/21
 */
public class MetaUUIDKeyGenerator extends BaseMetaKeyGenerator {

    public MetaUUIDKeyGenerator(String tableCode, String keyColumns) {
        super(tableCode, keyColumns);
    }

    @Override
    public void processBefore(Executor executor, MappedStatement ms, Statement stmt, Object parameter) {
        buildId(executor, ms, parameter);
    }

    @Override
    public void processAfter(Executor executor, MappedStatement ms, Statement stmt, Object parameter) {
        // do nothing
    }

    /**
     * 批量插入方法标识
     */
    private static final String BATCH_ID = "!MetaBaseMapper.insertBatch";

    private void buildId(Executor executor, MappedStatement ms, Object parameter) {

        final Configuration configuration = ms.getConfiguration();
        //插入的元数据
        final MetaObject metaParam = configuration.newMetaObject(parameter);

        if (BATCH_ID.equalsIgnoreCase(ms.getId())) {
            //批量插入
            List<Map<String, Object>> list = (List<Map<String, Object>>) metaParam.getValue(Constants.LIST_ALIAS);
            for (Map<String, Object> map : list) {
                // 生成 UUID 插入参数中
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                if (map.containsKey(keyColumns)) {
                    //元数据包含ID 则不自动生成
                    continue;
                }
                map.put(keyColumns, uuid);
                map.put(Constants.KEY_PK_VALUE, uuid);
            }
        } else {
            //普通插入
            if(!pkValueIsNull(metaParam)){
                return;
            }
            // 生成 UUID 插入参数中
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            ParameterUtil.setValue(metaParam, keyColumns, uuid);
            ParameterUtil.setValue(metaParam, Constants.KEY_PK_VALUE, uuid);
        }
    }

}
